const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');

// 窗口管理器
const windows = {
  main: null,
  devToolsWindow: null,
  normalWindow: null
};

function createMainWindow() {
  windows.main = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: false,
      contextIsolation: true
    }
  });

  windows.main.loadFile('index.html');
  windows.main.on('closed', () => {
    windows.main = null;
    if (!windows.devToolsWindow && !windows.normalWindow) {
      app.quit();
    }
  });
}

function createDevToolsWindow() {
  if (windows.devToolsWindow) {
    windows.devToolsWindow.focus();
    return;
  }

  windows.devToolsWindow = new BrowserWindow({
    width: 1000,
    height: 700,
    title: '调试窗口 - 开发者工具已打开',
    webPreferences: {
      devTools: true
    }
  });

  windows.devToolsWindow.loadURL('about:blank');
  windows.devToolsWindow.webContents.openDevTools({ mode: 'detach' });
  
  windows.devToolsWindow.on('closed', () => {
    windows.devToolsWindow = null;
    checkAppQuit();
  });
}

function createNormalWindow() {
  if (windows.normalWindow) {
    windows.normalWindow.focus();
    return;
  }

  windows.normalWindow = new BrowserWindow({
    width: 800,
    height: 600,
    title: '普通窗口 - 无开发者工具',
    webPreferences: {
      devTools: true
    }
  });

  windows.normalWindow.loadURL('about:blank');
  
  windows.normalWindow.on('closed', () => {
    windows.normalWindow = null;
    checkAppQuit();
  });
}

function checkAppQuit() {
  if (!windows.main && !windows.devToolsWindow && !windows.normalWindow) {
    app.quit();
  }
}

// IPC通信
ipcMain.handle('create-windows', () => {
  createDevToolsWindow();
  createNormalWindow();
  return { 
    devToolsWindow: !!windows.devToolsWindow,
    normalWindow: !!windows.normalWindow
  };
});

// 应用生命周期
app.whenReady().then(() => {
  createMainWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createMainWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});